<?php
namespace app\tag\model;
use think\Cache;
use app\common\lib\Paginationm;
use think\Db;
use think\Controller;

class Tags extends Controller
{
    protected $beforeActionList = ['start'];
    public function start() {
        $this->item = 'Tags';
        $this->itemType = 'tag';
        $this->itemName = '标签';
        $this->itemCategory = 'TagsCategory';
        $this->itemContent = 'TagsContent';
        $this->itemModelNameSpace = 'app\tag\model\Tags';
        $this->itemCategoryModelNameSpace = 'app\tag\model\TagsCategory';
    }
    
    public function itemAdd($paramData,$fieldList = [])
    {
        $itemInfo = db($this->item)->where('title',$paramData['title'])->find();
        if ($itemInfo) {
            return false;
        }
        $resArray = array (
        	'id' => uuid(),
            'cid' => $paramData['cid'] ? $paramData['cid'] : 0,
            'title' => $paramData['title'],
            'url_name' => $paramData['url_name'] ? $paramData['url_name'] : getPinyin($paramData['title']),
            'description' => $paramData['description'],
            'keywords' => $paramData['keywords'],
            'content' => htmlspecialchars($paramData['content']),
        );
        db($this->item)->insertGetId($resArray);
        return true;
    }

    public function itemEdit($paramData,$fieldList = [])
    {
        $itemInfo = db($this->item)->where('id',$paramData['id'])->find();
        if (!$itemInfo) {
            return false;
        }
        db($this->item)->where('id',$paramData['id'])->update(array (
            'title' =>  $paramData['title'],
            'url_name' => $paramData['url_name'] ? $paramData['url_name'] : getPinyin($paramData['title']),
            'description' => $paramData['description'],
            'keywords' => $paramData['keywords'],
            'content' => htmlspecialchars($paramData['content']),
        ));
        return true;
    }
    
    public function itemDel($id)
    {
        $itemInfo = db($this->item)->where('id',$id)->find();
        if (!$itemInfo) {
            return false;
        }
        db($this->item)->where('id',$id)->delete();
        return true;
    }
    
    public function getItemInfo($id = null)
    {
        if (!$id) {
            return false;
        }
        if (!$itemInfo) {
            $itemInfo = db($this->item)->where('id',$id)->find(); 
            if (!$itemInfo) {
                return false;
            }
        }
        if ($itemInfo) {
            $itemInfo['categoryInfo'] = model($this->itemCategoryModelNameSpace)->getCategoryInfo($itemInfo['cid']);
            $itemInfo['url'] = $this->getUrlByItemInfo($itemInfo);
            return $itemInfo;
        }
    }

    public function getItemListByTag($tag,$listType)
    {
        $tag = json_decode($tag,true);
        $whereArray = [];
        foreach ($tag as $key => $val) {
            if (strpos($key, 'where') !== false) {
                if (strpos($val, '=') !== false) {
                    $tempVal = explode('=', $val);
                    $whereArray[trim($tempVal[0])] = trim($tempVal[1]);
                }
                if (strpos($val, '<>') !== false) {
                    $tempVal = explode('<>', $val);
                    $whereArray[trim($tempVal[0])] = ['<>',trim($tempVal[1])];
                    break;
                }
                if (strpos($val, 'like') !== false) {
                    $tempVal = explode('like', $val);
                    $whereArray[trim($tempVal[0])] = ['like',trim($tempVal[1])];
                }
                if (strpos($val, '>') !== false) {
                    $tempVal = explode('>', $val);
                    $whereArray[trim($tempVal[0])] = ['>',trim($tempVal[1])];
                }
                if (strpos($val, '<') !== false) {
                    $tempVal = explode('<', $val);
                    $whereArray[trim($tempVal[0])] = ['<',trim($tempVal[1])];
                }
            }
        }
        $tag['whereArray'] = $whereArray;
        
        if ($listType == 'list') {
            return $this->getItemList($tag);
        }
        if ($listType == 'pagination') {
            return $this->getPagination($tag);
        }
        
    }
    public function getItemList($paramData)
    {
        $cid = $paramData['cid'] ? $paramData['cid'] : null;
        $page = $paramData['page'] ? $paramData['page'] : 1;
        $limit = $paramData['limit'] ? $paramData['limit'] : 10;
        $orderBy = $paramData['orderBy'] ? $paramData['orderBy'] : 'id';
        $order = $paramData['order'] ? $paramData['order'] : 'desc';
        $keywords = $paramData['keywords'] ? $paramData['keywords'] : null;
        $whereArray = $paramData['whereArray'] ? $paramData['whereArray'] : null;
        $itemIds = $paramData['itemIds'] ? $paramData['itemIds'] : null;
        $type = $paramData['type'] ? $paramData['type'] : null;
        
        if ($keywords) {
            $keywords = explode(',',$keywords);
            foreach ($keywords as $key => $val) {
                if ($val) {
                    $sq[] = "%".$val."%";
                }
            }
            $keywordsWhere['title']  = ['like',$sq,'OR'];
        }
        if (empty($ids)) {
            $idsWhere = null;
        } else {
            $ids = explode(',',$ids);
            $idsWhere['id']  = ['in',$ids];
        }
        
        if ($itemIds) {
            $itemList = [];
            $itemTags = db('TagsRel')->where('item_id','in',$itemIds)->select();
            if ($itemTags) {
                foreach ($itemTags as $k => $v) {
                    $tagInfo = db($this->item)->where('id',$v['tags_id'])->find();
                    if ($tagInfo) {
                        $itemList[] = $tagInfo;
                    } 
                }
            }
        } else {
            if ($cid == '' || $cid == null) {
                $cidWhere = null;
                $cidsWhere = null;
            } else {
                $cidWhere['cid'] = $cid;
                $data['pid'] = $cid;
                $itemCategoryList = model($this->itemCategoryModelNameSpace)->getCategory($data);
                if ($itemCategoryList) {
                    foreach ($itemCategoryList as $key => $value) {
                        $cids[] = $value['id'];
                    }
                    $cidsWhere['cid']  = ['in',$cids];
                }
            }
            $itemList = db($this->item)->where($keywordsWhere)->where($idsWhere)->where($cidWhere)->whereOr($cidsWhere)->where($whereArray)->page($page,$limit)->order($orderBy,$order)->select();
        }
        if ($itemList) {
            foreach($itemList as $k => $v) {
                $itemList[$k] = $this->getItemInfo($v['id'],$v);
            }
        } else {
            $itemList = [];
        }
        return $itemList;
    }
   
   public function getPagination($paramData)
   {
       $cid = $paramData['cid'] ? $paramData['cid'] : null;
       $page = $paramData['page'] ? $paramData['page'] : 1;
       $limit = $paramData['limit'] ? $paramData['limit'] : 10;
       $keywords = $paramData['keywords'] ? $paramData['keywords'] : null;
       $whereArray = $paramData['whereArray'] ? $paramData['whereArray'] : null;
       
       $count = $this->getCount($cid,$keywords,$whereArray);
       $categoryInfo = model($this->itemCategoryModelNameSpace)->getCategoryInfo($cid);
       $baseUrl = $categoryInfo['url'];
       $pagination_array = array(
           'base_url' => $baseUrl,
           'total_rows' => $count,
           'per_page' => $limit,
           'cur_page' => $page,
           'page_break' => '_'
       );
       $pagination = new Paginationm($pagination_array);
       return $pagination->create_links();
   }
    
    public function getCount($cid = null,$keywords = null,$whereArray = null)
    {
        if ($keywords) {
            $keywords = explode(',',$keywords);
            foreach ($keywords as $key => $val) {
                if ($val) {
                    $sq[] = "%".$val."%";
                }
            }
            $keywordsWhere['title']  = ['like',$sq,'OR'];
        }
        if ($cid == '' || $cid == null) {
            $cidWhere = null;
            $cidsWhere = null;
        } else {
            $cidWhere['cid'] = $cid;
            $data['pid'] = $cid;
            $itemCategoryList = model($this->itemCategoryModelNameSpace)->getCategory($data);
            if ($itemCategoryList) {
                foreach ($itemCategoryList as $key => $value) {
                    $cids[] = $value['id'];
                }
                $cidsWhere['cid']  = ['in',$cids];
            }
        }
        $count = db($this->item)->where($keywordsWhere)->where($cidWhere)->whereOr($cidsWhere)->count();
        return $count;
    }
    
    public function getContentByItemInfo($itemInfo,$type = null)
    {
        $itemInfo['content'] = htmlspecialchars_decode($itemInfo['content']);
        $itemInfo['mipContent'] = model('app\common\model\Common')->getContentFilterByContent($itemInfo['content']);
        return $itemInfo;
    }
    
    public function getUrlByItemInfo($item,$domain = null)
    {
        $tempId = $item['id'];
        $tempId = $item['url_name'] ? $item['url_name'] : $tempId;
        if (config('isTagName')) {
            $tempId = $item['name'];
        }
        $domain = $domain ? $domain : config('domain');
        $res = $domain . '/' . config('settingInfo')['tagModelUrl'] . '/' . $tempId . '/';
        return $res;
    }
    
}